package com.project.ping;



import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Ping {

    int timeOut = 5;
    boolean status = false;
    boolean pingStatus=true;
    ConcurrentLinkedQueue<Thread> arrayList = new ConcurrentLinkedQueue<>();
    ExecutorService threadPool = Executors.newFixedThreadPool(5);

    Ping() {
        JFrame jFrame = new JFrame();
        jFrame.setLocationRelativeTo(null);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(900, 600);
        Dimension dimension = jFrame.getToolkit().getScreenSize();
        double width=(dimension.getWidth()-jFrame.getSize().getWidth())/2;
        double height=(dimension.getHeight()-jFrame.getSize().getHeight())/2;
        jFrame.setLocation((int) width,(int)height);
        jFrame.setTitle("ping");

        JLabel jLabel = new JLabel("");
        JTextArea jTextArea = new JTextArea(5, 8);
        jTextArea.setLineWrap(true);
        File file = new File("D:\\ping\\ipList.txt");
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }

        JPanel jPanelButton = new JPanel();
        jPanelButton.setSize(300,75);
        JPanel jPanelInterval = new JPanel(new FlowLayout());
        jPanelInterval.setSize(300,75);
        JPanel jPanelFather = new JPanel(new BorderLayout());
        jPanelFather.setSize(300,150);

        JPanel jPanelLabel = new JPanel();
        JPanel jPanelText = new JPanel(new BorderLayout());
        jPanelLabel.add(jLabel);


        JScrollPane jScrollPane = new JScrollPane(jPanelText);
        JScrollBar scrollBar = jScrollPane.getVerticalScrollBar();

        String[] ipLists = properties.getProperty("IPList").split(";");
        String text = "";
        for (int i = 0; i < ipLists.length; i++) {
            jTextArea.append(ipLists[i]);
            jTextArea.append("\n");
            scrollBar.setValue(scrollBar.getMaximum());
        }

        JTextField jTextinterval=new JTextField();
        jTextinterval.setPreferredSize(new Dimension(50,30));
        JRadioButton jRadioAdvice=new JRadioButton();
        JLabel jLabelAdvice=new JLabel("advice");

        JButton interval_jButton = new JButton("set");
        interval_jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String s = jTextinterval.getText();
                timeOut=Integer.parseInt(s);
                jTextArea.append("set interval time="+timeOut+"s\n");
                scrollBar.setValue(scrollBar.getMaximum());
            }
        });
        JButton ping_jButton = new JButton("ping");
        ping_jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                pingStatus=true;
                if (!status) {
                    status = !status;
                    ping_jButton.setText("stop");
                    File file1 = new File("D:\\ping\\ipList.txt");
                    Properties properties1 = new Properties();
                    try {
                        properties1.load(new FileInputStream(file));
                        String IPList = properties1.getProperty("IPList");
                        String[] split = IPList.split(";");
                        for (int i = 0; i < split.length; i++) {
                            String s = split[i];
                            if (split[i].contains(";")) {
                                split[i].replaceAll(";", "");
                            }
                            threadPool.execute(new Runnable() {
                                @Override
                                public void run() {

                                    OutputStream outputStream = null;
                                    BufferedWriter bufferedWriter = null;
                                    try {
                                        File file1 = new File("D:\\ping\\log\\" + s + ".txt");
                                        if (!file1.exists()) {
                                            file1.createNewFile();
                                        }
                                        outputStream = new FileOutputStream(file1, true);
                                        bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "GBK"));
                                        boolean pingStatusTemp=true;
                                        int count=1;
                                        while (pingStatusTemp) {
                                            synchronized (this){
                                                pingStatusTemp=pingStatus;
                                                System.out.println("pingStatusTemp:"+pingStatusTemp);
                                            }
                                            Process process = null;
                                            process = Runtime.getRuntime().exec("ping " + s);
                                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
                                            bufferedWriter.write("************************分隔符**************************");
                                            bufferedWriter.flush();
                                            bufferedWriter.write("\r\n");
                                            bufferedWriter.flush();
                                            bufferedWriter.write(new Date().toString());
                                            bufferedWriter.write("\r\n");
                                            String buff;
                                            boolean isOk = false;
                                            jTextArea.append("\n");
                                            while ((buff = bufferedReader.readLine()) != null) {
                                                jTextArea.append(buff+"\n");
                                                scrollBar.setValue(scrollBar.getMaximum());
                                                if (buff.contains("来自")) {
                                                    isOk = true;
                                                }
                                                bufferedWriter.write(buff);
                                                bufferedWriter.write("\r\n");
                                                bufferedWriter.flush();
                                            }
                                            jTextArea.append("\n\n");
                                            if (!isOk) {
                                                jLabel.setText(s + "  未ping通!("+count+"次)");
                                                System.out.println("选中:"+jRadioAdvice.isSelected());
                                                if (jRadioAdvice.isSelected()) {
                                                    DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
                                                    String desp="**[失败IP:"+s+"]**===***失败第"+count+"次,请及时查看和处理!***==="+dateFormat.format(new Date());
                                                    String url="https://sc.ftqq.com/SCU54180Td06b3cca18c70eb64e700a55a9d536655d1289714a684.send?text=PING失败&desp="+desp;
                                                    HttpURLConnection conn = (HttpURLConnection)(new URL(url)).openConnection();

                                                    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                                                    StringBuilder sb = new StringBuilder();
                                                    for (int c; (c = in.read()) >= 0;) {
                                                        sb.append((char)c);
                                                    }
                                                    System.out.println(sb.toString());
                                                    in.close();

                                                    conn.disconnect();
                                                }
                                                count++;
                                                for (int i = 0; i < 6; i++) {
                                                    Toolkit.getDefaultToolkit().beep();
                                                    Thread.sleep(700);
                                                }
                                            }
                                            bufferedReader.close();
                                            Thread.sleep(timeOut * 1000);

                                        }
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            });
                        }

                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                } else {
                    status = !status;
                    ping_jButton.setText("ping");
                    jLabel.setText("");
                    pingStatus=false;

                }


            }
        });


        jPanelButton.add(ping_jButton);

        jPanelInterval.add(jTextinterval);
        jPanelInterval.add(interval_jButton);
        jPanelInterval.add(jRadioAdvice);
        jPanelInterval.add(jLabelAdvice);


        jPanelFather.add(jPanelInterval,BorderLayout.NORTH);
        jPanelFather.add(jPanelButton,BorderLayout.SOUTH);

        jPanelText.add(jTextArea);


        jFrame.add(jScrollPane, BorderLayout.CENTER);
        jFrame.add(jPanelFather, BorderLayout.SOUTH);
        jFrame.add(jPanelLabel, BorderLayout.NORTH);
        jFrame.setVisible(true);


    }

    public static void main(String[] args) {
        File file = new File("D:\\ping");
        if (!file.exists()) {
            file.mkdir();
        }
        File file1 = new File("D:\\ping\\log");
        if (!file1.exists()) {
            file1.mkdir();
        }
        File file2 = new File("D:\\ping\\ipList.txt");
        Properties properties1 = new Properties();
        if (!file2.exists()) {
            try {
                file2.createNewFile();
                properties1.setProperty("IPList", "www.baidu.com;123.56.134.30");
                OutputStream outputStream = new FileOutputStream(file2);
                properties1.store(outputStream, "");
                outputStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        Ping ping = new Ping();

    }
}
